package com.pai4j.ugc.service.community;

import com.pai4j.common.constants.WebConstant;
import com.pai4j.common.enums.RedisKeyEnum;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.common.util.RedisUtil;
import com.pai4j.ugc.repository.dao.ICommunityContributionDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区共建统计服务类
 *
 * @author: CYM-pai
 * @date: 2025/07/30 12:00
 **/
@Slf4j
@Service
public class CommunityContributionStatisticsService {

    @Autowired
    private ICommunityContributionDAO contributionDAO;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取统计信息
     *
     * @return 统计信息
     */
    public Map<String, Object> getStatistics() {
        // 1. 先从缓存中获取统计信息
        Map<String, Object> statistics = this.findStatisticsFromCache();
        if (statistics == null) {
            // 缓存不存在主动查询数据库
            statistics = this.calculateStatistics();
            // 刷新缓存
            this.refreshStatisticsCache(statistics);
        }
        
        return statistics;
    }

    /**
     * 获取用户仪表板数据
     *
     * @param userId 用户ID
     * @return 仪表板数据
     */
    public Map<String, Object> getUserDashboard(String userId) {
        Map<String, Object> dashboard = new HashMap<>();
        
        // 用户提交的共建统计
        List<Object[]> submitterStats = contributionDAO.countByStatus();
        Map<String, Long> submitterStatusCount = new HashMap<>();
        for (Object[] stat : submitterStats) {
            submitterStatusCount.put(String.valueOf(stat[0]), (Long) stat[1]);
        }
        dashboard.put("submitterStatusCount", submitterStatusCount);
        
        // 用户处理的共建统计（如果是管理员）
        // 这里可以根据用户角色来决定是否显示
        dashboard.put("assigneeStatusCount", submitterStatusCount);
        
        // 总体统计
        dashboard.put("totalStatistics", this.getStatistics());
        
        return dashboard;
    }

    /**
     * 刷新统计缓存
     */
    public void refreshStatisticsCache() {
        Map<String, Object> statistics = this.calculateStatistics();
        this.refreshStatisticsCache(statistics);
    }

    /**
     * 计算统计信息
     */
    private Map<String, Object> calculateStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 按状态统计
        List<Object[]> statusStats = contributionDAO.countByStatus();
        Map<String, Long> statusCount = new HashMap<>();
        for (Object[] stat : statusStats) {
            statusCount.put(getStatusName((Integer) stat[0]), (Long) stat[1]);
        }
        statistics.put("statusCount", statusCount);
        
        // 按类型统计
        List<Object[]> typeStats = contributionDAO.countByType();
        Map<String, Long> typeCount = new HashMap<>();
        for (Object[] stat : typeStats) {
            typeCount.put(getTypeName((Integer) stat[0]), (Long) stat[1]);
        }
        statistics.put("typeCount", typeCount);
        
        // 按优先级统计
        List<Object[]> priorityStats = contributionDAO.countByPriority();
        Map<String, Long> priorityCount = new HashMap<>();
        for (Object[] stat : priorityStats) {
            priorityCount.put(getPriorityName((Integer) stat[0]), (Long) stat[1]);
        }
        statistics.put("priorityCount", priorityCount);
        
        // 总数统计
        long totalCount = contributionDAO.count();
        statistics.put("totalCount", totalCount);
        
        return statistics;
    }

    /**
     * 从缓存中获取统计信息
     */
    private Map<String, Object> findStatisticsFromCache() {
        String cacheKey = RedisKeyEnum.COMMUNITY_CONTRIBUTION_STATISTICS.getKey();
        String cacheValue = redisUtil.get(cacheKey);
        if (StringUtils.hasText(cacheValue) && !WebConstant.CACHE_NONE.equals(cacheValue)) {
            return JsonUtil.toMap(cacheValue);
        }
        return null;
    }

    /**
     * 刷新统计缓存
     */
    private void refreshStatisticsCache(Map<String, Object> statistics) {
        String cacheKey = RedisKeyEnum.COMMUNITY_CONTRIBUTION_STATISTICS.getKey();
        redisUtil.set(cacheKey, JsonUtil.toJsonString(statistics), RedisKeyEnum.COMMUNITY_CONTRIBUTION_STATISTICS.getExpireTime());
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        switch (status) {
            case 1: return "已提交";
            case 2: return "审核中";
            case 3: return "已接受";
            case 4: return "进行中";
            case 5: return "已完成";
            case 6: return "已拒绝";
            default: return "未知状态";
        }
    }

    /**
     * 获取类型名称
     */
    private String getTypeName(Integer type) {
        switch (type) {
            case 1: return "需求";
            case 2: return "缺陷";
            default: return "未知类型";
        }
    }

    /**
     * 获取优先级名称
     */
    private String getPriorityName(Integer priority) {
        switch (priority) {
            case 1: return "低";
            case 2: return "中";
            case 3: return "高";
            case 4: return "紧急";
            default: return "未知优先级";
        }
    }
}
